<template>
  <div class="replacecard">
    <!-- 卡号 -->
    <div class="cardOrder">
      <div class="contentcard" style="position:relative;">
        <span style="padding-right:0.3rem ">卡号</span>
        <input class="inp" maxlength="23" @input="ycardvalue = ycardvalue.replace(/[^\d]/g,'');" type="tel"
               placeholder="请输入16、19或20位卡号" v-model="ycardvalue">
        <img @click="ycardvalue='' " v-show="ycardvalue.length>0" src="../img/cc@2x.png" alt="">
      </div>
    </div>
    <!-- 姓名 -->
    <div class="cardOrder" style="margin-top:0.32rem;">
      <div class="contentcard" style="position:relative;">
        <span style="padding-right:0.3rem ">姓名</span>
        <input class="inp" maxlength="23" placeholder="请输入姓名" type="text" v-model="newCardValue">
        <img @click="newCardValue='' " v-show="newCardValue.length>0" src="../img/cc@2x.png" alt="">
      </div>
    </div>
    <!-- 证件类型 -->
    <div class="cardOrder">
      <div class="contentcard" @click="showPopup" style="position:relative;">
        <span>证件类型</span>
        <p class="certificate">身份证</p>
        <img class="xh" src="../img/icon.png" alt="">
      </div>
    </div>
    <!-- 证件号 -->
    <div class="cardOrder">
      <div class="contentcard" style="position:relative;">
        <span>证件号</span>
        <input class="inp" maxlength="18" @input="certificate" placeholder="请输入身份证号码" type="text" v-model="IdNumder">
        <img @click="IdNumder='' " v-show="IdNumder.length>0" src="../img/cc@2x.png" alt="">
      </div>
    </div>
    <!-- 手机号 -->
    <div class="cardOrder">
      <div class="contentcard">
        <span>手机号</span>
        <input class="inp" maxlength="11" @input="phoneNumber = phoneNumber.replace(/[^\d]/g,'');"
               placeholder="请输入绑定的手机号" type="tel" v-model="phoneNumber">
        <img @click="phoneNumber='' " v-show="phoneNumber.length>0" src="../img/cc@2x.png" alt="">
      </div>
    </div>
    <!-- 支付密码 -->
    <div class="cardOrder" style="margin-top:0.32rem;">
      <div class="contentcard">
        <span>支付密码</span>
        <input class="inp" style="padding-left:0rem " @click='clickLink' readonly='readonly' type="Password"
               name="passwd" placeholder='请输入支付密码' id="dncodPasswd">
        <img v-show="lent*1>0" @click="close" src="../img/cc@2x.png" alt="">
      </div>
    </div>
    <div :class="pitch?'btns':'nextStep'" @click="buts">
      下一步
    </div>
    <!-- 弹框 -->
    <div v-if="shadeOpen" class="shade">
      <div class="backcolor">
        <h3>提示</h3>
        <p>确认提交挂失信息?</p>
        <div class="butndiv">
          <div class="qxbut" @click="shadeOpen=false">取消</div>
          <div class="qrbut" @click="confirm">确认</div>
        </div>
      </div>
    </div>
    <!-- 证件类型选择 -->
    <van-popup v-model="show" duration='0.2' position="bottom">
      <div class="certifis">
        <div class="cont">身份证</div>
      </div>
    </van-popup>
  </div>
</template>

<script>
let u = navigator.userAgent;
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
import Vue from 'vue';
import {Toast} from 'vant';

Vue.use(Toast);
export default {
  data() {
    return {
      ycardvalue: '',//卡号
      newCardValue: '',//新卡号
      IdNumder: '',//证件号
      phoneNumber: '',//手机号
      Passwords: '',//输入的密码
      random: '',//随机数
      lent: 0,//长度
      shadeOpen: false,//遮罩
      show: false,
      domain: '',//域名
      repPathUrl: '',//广告域名
      Authorization: '',//Basic c3dvcmQ6c3dvcmRfc2VjcmV0
      tokenPassword: '',//广告密码
      tokenName: '',//广告名字
      hubBaseUrl: '',//hub平台
      facility: '',//唯一标识
      clientType: '',//手机类型
      userinfolist: '',//登录信息
      token: '',//token获取
    }
  },
  computed: {
    pitch: function () {
      if (this.ycardvalue && this.newCardValue && this.IdNumder && this.phoneNumber && this.Passwords) {
        return true
      } else {
        return false
      }
    },
  },

  mounted() {
    BmacJSBridge.call('YKTSafeControlClearPassword', {keyboardId: 'dncodPasswd'});
    let _this = this
    document.addEventListener('YKTSafeControlChangeValue', (e) => {
      if (e.data.keyboardId == 'dncodPasswd') {
        let text = e.data.text;
        let field = document.getElementById('dncodPasswd');
        field.value = text;
        _this.Passwords = e.data.password;
        _this.random = e.data.randomKey
        _this.lent = e.data.length
      }
    }, false);
    setTimeout(() => {
      BmacJSBridge.call('obtainClientBaseUrl', seft => {
        this.domain = seft.pay3BaseUrl
        this.repPathUrl = seft.adBaseUrl
        this.Authorization = seft.Authorization
        this.tokenPassword = seft.adTokenPassword
        this.tokenName = seft.adTokenName
        this.hubBaseUrl = seft.hubBaseUrl
        // 获取手机型号
        if (isAndroid) {
          this.clientType = "Android";
        } else {
          this.clientType = "ios";
        }
        // 获取登录信息
        BmacJSBridge.call('getAPDataStorage', {
          type: "common",
          business: "userInfoGrid",
          key: "userInfo",
        }, (result) => {
          if (result.error == '11' && result.errorMessage == '未找到该数据') {
            // this.loginopen=false
            // this.userinfolist={}
          } else {
            console.log("获取登录信息1", JSON.parse(result.data).data)
            // this.loginopen=true
            this.userinfolist = JSON.parse(result.data).data
            this.token = this.userinfolist.token_type + " " + this.userinfolist.access_token

          }
        })
        // 获取手机唯一标识
        BmacJSBridge.call('getBasicInfo', (data) => {//获取手机唯一标识等
          console.log("获取手机唯一表示", data)
          this.facility = data.deviceData

        });
      })
    }, 200)
  },
  methods: {

   async confirm() {//确认
      let embedding = {
        eventID: "goAccountlose",
        extra: {
          name: "账户挂失-下一步"
        },
      };
      BmacJSBridge.call("AddEventburyPoints", embedding, (data) => {
      })
      let initInfo = await this.getAPPConfigureInfo()
      let basicInfo = await  this.getBasicInfo()

      var body = {
        idType: '1',                          //证件类型
        channelType: 'MOB',                    //渠道类型
        merId: '003070000001',                 //商户号
        clientType: this.clientType,           //客户端类型weex.config.env.osName //this.clientType
        passWord: this.Passwords,            //支付密码
        customerId: this.userinfolist.customerId,    //客户号
        identifyId: this.IdNumder,           //证件号
        lostType: '1',                         //挂失类型
        srandNum: this.random,               //加密随机数
        channelId: "75111023",                 //渠道号
        encFlag: '2',                          //加密标识
        mobileNo: this.phoneNumber,             //手机号
        logonId: this.userinfolist.logonIds,        //登陆名
        cardNo: this.ycardvalue,                //卡号
        name: this.newCardValue,                 //姓名
        version: initInfo.encryptControl == '01' ? basicInfo.version : '',
      };
      console.log("1挂失参数", body)
     if(initInfo.encryptControl == '01'){
       BmacJSBridge.call("encryptDataWithGuomi", body, datay => {
         this.$ajax({
           method: "post",
           url: this.domain + '/wolf-customer/customer/qyzhgs',
           data: {
             data:datay.encryptedData,
             deviceId:basicInfo.imei,
             channelId:'BMAC',
             authenticator:'SM4',
           },
           headers: {
             'Content-Type': 'application/json',
             'Authorization': this.Authorization,
             'wolf-auth': this.token
           },
         }).then(res => {
           BmacJSBridge.call("decryptDataWithGuomi", {decryptParam: res.data.data}, (databut) => {
             let starts = JSON.parse(decodeURIComponent(databut.encryptedData));
             console.log("确定换卡返回", starts)

             if (starts.data.retCode == '9001') {
               Toast("网络开小差");
               return
             } else {

               this.$router.push({path: '/results', query: {id: JSON.stringify(starts.data), No: 2}})

             }

           })
         }).catch(error => {
           if (error.response) {
             BmacJSBridge.call("decryptDataWithGuomi", {decryptParam: error.response.data},
               databut => {
                 let request = JSON.parse(decodeURIComponent(databut.encryptedData));
                 // console.log("错误", request);
                 if (request.code == 401) {
                   var text = request.msg || request.message;
                   Toast(text);
                   setTimeout(() => {
                     BmacJSBridge.call('startApp', {
                       appId: '00000060',
                       type: '1',
                       passData: {},
                       url:'',
                       closeCurrentApp: true
                     }, function (result) {
                       // noop
                     });
                   }, 2000);
                 }
               }
             );
           } else {
             this.ticketListopen = false;
             Toast("网络开小差");
           }
         })
       })
     }else {
       BmacJSBridge.call("encryptDataWithRSA3", body, datay => {
         this.$ajax({
           method: "post",
           url: this.domain + '/wolf-customer/customer/qyzhgs',
           data: datay.encryptedData,
           headers: {
             'Content-Type': 'application/json',
             'Authorization': this.Authorization,
             'wolf-auth': this.token
           },
         }).then(res => {
           BmacJSBridge.call("decryptDataWithRSA3", {decryptParam: res.data}, (databut) => {
             let starts = databut.encryptedData;
             console.log("确定换卡返回", starts)

             if (starts.data.retCode == '9001') {
               Toast("网络开小差");
               return
             } else {

               this.$router.push({path: '/results', query: {id: JSON.stringify(starts.data), No: 2}})

             }

           })
         }).catch(error => {
           if (error.response) {
             BmacJSBridge.call("decryptDataWithRSA3", {decryptParam: error.response.data},
               databut => {
                 let request = databut.encryptedData;
                 // console.log("错误", request);
                 if (request.code == 401) {
                   var text = request.msg || request.message;
                   Toast(text);
                   setTimeout(() => {
                     BmacJSBridge.call('startApp', {
                       appId: '00000060',
                       type: 1,
                       closeCurrentApp: true
                     }, function (result) {
                       // noop
                     });
                   }, 2000);
                 }
               }
             );
           } else {
             this.ticketListopen = false;
             Toast("网络开小差");
           }
         })
       })
     }

    },

    /**
     * 获取引用初始化接口参数
     */
    getAPPConfigureInfo() {
      return new Promise((resolve, reject) => {
        BmacJSBridge.call("getAPPConfigureInfo", (data) => {
          resolve(data)
        })
      })
    },

    /**
     * 获取基本信息
     */
    getBasicInfo() {
      return new Promise((resolve, reject) => {
        BmacJSBridge.call("getBasicInfo", {}, (data) => {
          let phoneData = data.deviceData;
          resolve(phoneData)
        });
      })

    },
    buts() {//下一步
      // this.shadeOpen=true
      if (this.pitch) {
        if (/^31|10/.test(this.ycardvalue)) {
          if (this.ycardvalue.length == 16 || this.ycardvalue.length == 19 || this.ycardvalue.length == 20 || this.ycardvalue.length == 23) {
            if (/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/.test(this.IdNumder)) {
              if (this.IdNumder.length == 15 || this.IdNumder.length == 18) {
                if (this.phoneNumber.length == '11') {
                  if (this.lent == 6) {
                    this.shadeOpen = true
                  } else {
                    Toast("请输入正确密码");
                  }
                } else {
                  Toast("请输入正确手机号");
                }
              } else {
                Toast("请输入正确证件号");
              }
            } else {
              Toast("请输入正确证件号");
            }

          } else {
            Toast("请输入正确卡号");
          }
        } else {
          Toast("请输入正确卡号");
        }
      }
    },
    showPopup() {
      this.show = true;

    },
    certificate(e) {//证件号校验
      let pattern = new RegExp("[^x|X|0-9]")
      console.log("证件", e.target.value)
      let str = e.target.value;
      let inputVal = "";
      for (var i = 0; i < str.length; ++i) {
        inputVal = inputVal + str.substr(i, 1).replace(pattern, '');
      }
      this.IdNumder = inputVal.replace(/[.]/g, '');
    },
    async  clickLink(e) {//调密码键盘
      let tag = e.currentTarget.id
      let initInfo = await this.getAPPConfigureInfo()
      BmacJSBridge.call('YKTSafeControlShow', {
        keyboardType: 0,//4-数字 其他
        passLength: 6,
        keyOrderType: 0,//0正常 1乱序 2切换乱序
        keyPressStype: 1,
        isShowToolBar: false,
        keyboardMode: true,//false 显示星号
        isDotDelay: true,
        isHasStatus: true,
        isEnablePaste: true,
        keyboardId: tag,
        isGuomi:initInfo.encryptControl == '01'? '1': '0'

      }, (data) => {
        // alert('GGG：'+JSON.stringify(data));
      });
    },
    close() {//清空密码
      BmacJSBridge.call('YKTSafeControlClearPassword', {keyboardId: 'dncodPasswd'}, (data) => {
      });
      let field = document.getElementById('dncodPasswd');
      field.value = '';
    },
  },
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../../../common/stylus/mixin.styl';
.replacecard {
  height 100%;
  width 100%;
  padding-top: 0.32rem;
  box-sizing: border-box

  .cardOrder {
    width 100%;
    height 1.04rem;
    background #ffffff;
    padding-left: 0.32rem;
    box-sizing: border-box;

    .contentcard {
      width 100%;
      height 1.04rem;
      display flex;
      align-items center;
      justify-content space-between;
      background #ffffff;
      padding-right: 0.32rem;
      box-sizing: border-box;

      .inp {
        height 1.04rem;
        flex 1;
        font-size 14px;
        outline: none;
        padding-left: 0.3rem
      }

      span {
        font-size 0.32rem;
        margin-right 0.3rem;
      }

      img {
        width 0.32rem;
        height 0.32rem;
      }

      .certificate {
        font-size 0.32rem;

        flex: 1;
      }

      .xh {
        height 0.16rem;
        width 0.24rem
      }
    }

    .contentcard:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0rem;
      background: #e6e6e6;
      width: 100%;
      height: 1px;
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
      -webkit-transform-origin: 0 0;
      transform-origin: 0 0;
    }
  }

  .nextStep {
    background: #D9D9D9;
    border-radius: 4px;
    font-size 0.32rem;
    margin: 0 0.32rem;
    height 0.88rem;
    text-align center;
    line-height 0.88rem;
    margin-top: 0.32rem
    color #ffffff;
  }

  .btns {
    background: #008DEE;
    border-radius: 4px;
    font-size 0.32rem;
    margin: 0 0.32rem;
    height 0.88rem;
    text-align center;
    line-height 0.88rem;
    margin-top: 0.32rem
    color #ffffff;
  }

  .shade {
    position absolute;
    left 0;
    top: 0;
    width 100%;
    height 100%;
    background rgba(0, 0, 0, .3);
    display flex;
    justify-content center;
    align-items center;

    .backcolor {
      border-radius: 6px;
      width 80%;
      height 3.5rem;
      background: #ffffff;
      display flex;
      flex-direction column;

      h3 {
        font-size 18px;
        margin-top 0.4rem;

        text-align center;
      }

      p {
        flex 1;
        font-size 16px;
        text-align center;
        padding-top: 0.5rem;
      }

      .butndiv {
        height 1rem;
        display flex;
        // justify-content space-around;
        // align-items center;
        font-size 18px;
        position relative;
      }

      .qxbut {
        width 50%;
        display flex;
        justify-content center;
        align-items center;
        color: #999999
      }

      .qrbut {
        width 50%;
        display flex;
        justify-content center;
        align-items center;
        color: #008DEE;
        position relative
      }

      .butndiv:after {
        content: '';
        position: absolute;
        top: 0;
        left: 0rem;
        background: #e6e6e6;
        width: 100%;
        height: 1px;
        -webkit-transform: scaleY(0.5);
        transform: scaleY(0.5);
        -webkit-transform-origin: 0 0;
        transform-origin: 0 0;
      }

      .qrbut:after {
        content: '';
        position: absolute;
        top: 0;
        left: 0rem;
        background: #e6e6e6;
        width: 1px;
        height: 100%;
        -webkit-transform: scaleX(0.5);
        transform: scaleX(0.5);
        -webkit-transform-origin: 0 0;
        transform-origin: 0 0;
      }
    }
  }
}

.certifis {
  height 2rem;
  padding: 0 0.32rem;

  .cont {
    font-size 14px;
    height: 1.04rem;
    text-align center;
    line-height 1.04rem;
    position relative
  }

  .cont:after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0rem;
    background: #e6e6e6;
    width: 100%;
    height: 1px;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
  }
}
</style>
